<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class ModelLogin extends MY_AdminModel
{
    function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('security');
    }

    public function login($user, $pass)
    {
        if (empty($user)) {
            return $this->lang->line('error_username_empty');
        }
        if (empty($pass)) {
            return $this->lang->line('error_password_empty');
        }
        $pass = do_hash($pass);
        $query = $this->db->query("SELECT * FROM {$this->map->user} WHERE BINARY {$this->map->user()->Username}=? AND BINARY {$this->map->user()->Password} =?", array($user, $pass));
        if ($query->num_rows() == 1) {
            $row = $query->row_array(1);
            if ($row[$this->map->user()->Activated] == '0') {
                return $this->lang->line('error_account_not_activated');
            }
            if ($row[$this->map->user()->Deleted] == '1') {
                return $this->lang->line('error_account_was_deleted');
            }
            if (isset($row[$this->map->user()->ID]) && array_key_exists($this->map->user()->Key, $row)) {
                $key = do_hash(time()) . rand(10009, 99999);
                $query = $this->db
                    ->where(array(
                        $this->map->user()->ID => $row[$this->map->user()->ID]
                    ))
                    ->update($this->map->user, array(
                        $this->map->user()->Key => $key
                    ));
                if ($query) {
                    $row[$this->map->user()->Key] = $key;
                }
            }
            return $row;
        }
        return $this->lang->line('error_username_password_not_match');
    }

    public function checkLogin($userInfo)
    {
        if (isset($userInfo[$this->map->user()->ID]) && isset($userInfo[$this->map->user()->Username]) && isset($userInfo[$this->map->user()->Password]) && isset($userInfo[$this->map->user()->Key])) {
            $query = $this->db->query(
                "SELECT * FROM {$this->map->user} WHERE {$this->map->user()->ID}=? AND BINARY {$this->map->user()->Username}=? AND BINARY {$this->map->user()->Password}=? AND BINARY {$this->map->user()->Key}=?",
                array($userInfo[$this->map->user()->ID],
                    $userInfo[$this->map->user()->Username],
                    $userInfo[$this->map->user()->Password],
                    $userInfo[$this->map->user()->Key]
                )
            );
            if ($query->num_rows() == 1) {
                return TRUE;
            }
        }
        return FALSE;
    }

}